package com.xintool.window.Buttons;

import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.plaf.basic.BasicProgressBarUI;
import javax.swing.plaf.basic.BasicSliderUI;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class Button_jpq extends ButtonFactory {

    private static JFrame frame;
    private int remainingEnemies = 6; // 初始默认6个精灵
    private JLabel counterLabel; // 原 createStatusPanel() 中的局部变量升级为成员变量

    //结果面板
    private JTextPane resultTextPane;

    // 新增复选框相关成员变量
    private JCheckBox checkBeikezhi;
    private JCheckBox checkKezhi;
    private JCheckBox checkWeiruo;
    private JCheckBox checkWuxiao;
    private static final int[] WIDTH_BY_SELECTION = {310, 410, 450};//根据选择数量调整窗口宽度

    private static final String[] DEFAULT_SELECTIONS = {
            "丽莎布布", "魔焰猩猩", "鲁斯王", "电", "飞", "地"
    };
    private static final String[] DEFAULT_SPIRITS = {"火", "水", "草", "飞", "电", "地", "机械", "冰", "超能", "普通", "战斗", "暗影", "光", "龙", "神秘","丽莎布布", "魔焰猩猩", "鲁斯王"};

    private static Map<String, Map<String, Double>> restraintMap = new HashMap<>();// 完整关系表
    private static double[][] RELATION_MATRIX = new double[16][16]; // 初始化为空矩阵
    @Override
    public JButton showButton() {
        JButton button = ButtonFactory.getButton("记牌器");
        button.addActionListener(e -> createMainWindow());
        return button;
    }

    public void createMainWindow() {

        if (frame != null && frame.isDisplayable()) {
            frame.toFront();
            return;
        }

        frame = new JFrame("PVP手动记牌器");
        frame.setSize(310, 580);
        frame.setLayout(new BorderLayout(10, 10));
        //frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        loadRelationMatrixFromTextFile(); // 从文件加载关系矩阵
        initRelations();//初始化数据到map中

        //主内容面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));


        // 生成6个精灵面板（根据DEFAULT_SELECTIONS数量）
        for (int i = 0; i < DEFAULT_SELECTIONS.length; i++) {
            mainPanel.add(createSpiritPanel(i));
            mainPanel.add(Box.createRigidArea(new Dimension(0, 13)));
        }

        // 状态面板（剩余精灵+重置按钮）
        JPanel statePanel = new JPanel(new GridLayout(1, 3, 5, 5));
        statePanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
        ));

        // 剩余标签居左
        counterLabel = new JLabel("剩余：" + remainingEnemies);
        counterLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        statePanel.add(counterLabel, new FlowLayout(FlowLayout.LEFT));
        // 重置和置顶按钮居右
        JButton resetBtn = new JButton("重置");
        resetBtn.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        //设置按钮大小
        resetBtn.setPreferredSize(new Dimension(90,27));
        JToggleButton topBtn = new Button_top(frame).showButton();
        resetBtn.setMargin(new Insets(2, 1, 2, 1)); // 增加内边距
        topBtn.setMargin(new Insets(2, 1, 2, 1)); // 增加内边距
        //resetBtn.setBounds(0,0,50,20);//设置按钮大小以及位置
        resetBtn.addActionListener(e -> resetAll());
        statePanel.add(resetBtn, BorderLayout.EAST);
        statePanel.add(topBtn);//置顶
        mainPanel.add(statePanel, BorderLayout.SOUTH);


        // 底部控制面板
        JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
        bottomPanel.setBorder(BorderFactory.createTitledBorder("克制关系"));
        bottomPanel.add(createResultPanel(), BorderLayout.CENTER);

        frame.add(mainPanel, BorderLayout.CENTER);
        frame.add(bottomPanel, BorderLayout.SOUTH);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        updateResultPanel();
    }

    private JPanel createSpiritPanel(int index) {
        JPanel panel = new JPanel(new BorderLayout(5, 5)) {
            @Override
            public Dimension getMaximumSize() {
                return new Dimension(Integer.MAX_VALUE, 65);
            }
        };
        // 下拉框
        JComboBox<String> spiritCombo = new JComboBox<>(DEFAULT_SPIRITS);
        spiritCombo.putClientProperty("defaultIndex", index);
        spiritCombo.setSelectedItem(DEFAULT_SELECTIONS[index]);
        spiritCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        spiritCombo.setPreferredSize(new Dimension(90, 27));
        spiritCombo.setMaximumRowCount(15);
        spiritCombo.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent e) {
                SwingUtilities.invokeLater(() -> {
                    // 递归查找滚动面板
                    Component popup = (Component) spiritCombo.getUI().getAccessibleChild(spiritCombo, 0);
                    if (popup instanceof BasicComboPopup) {
                        JList<?> list = ((BasicComboPopup) popup).getList();
                        list.ensureIndexIsVisible(0); // 强制显示第一项
                    }
                });
            }

            @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
            @Override public void popupMenuCanceled(PopupMenuEvent e) {}
        });


        // 血条面板（叠加布局）
        JPanel hpPanel = new JPanel() {
            @Override
            public boolean isOptimizedDrawingEnabled() {
                return false; //确保允许组件重叠绘制
            }
        };

        // 设置 OverlayLayout，传入已初始化的 hpPanel
        hpPanel.setLayout(new OverlayLayout(hpPanel));

        // 血条组件
        // 创建一个进度条对象，最小值为0，最大值为100
        JProgressBar hpBar = new JProgressBar(0, 100) {
            @Override
            public void updateUI() {
                // 锁定UI防止被系统主题覆盖
                setUI(new ReverseProgressBarUI());
            }
        };
        // 设置进度条的当前值为100，表示满血
        hpBar.setValue(100);

        // 显示百分比
        hpBar.setStringPainted(true);
        // 设置进度条上显示的字符串内容为"100%"
        hpBar.setString("100%");
        hpBar.setForeground(Color.BLACK); // 确保文字可见

        // 设置进度条的前景色为绿色，RGB值为(76, 175, 80)
        hpBar.setForeground(new Color(76, 175, 80)); // 绿色血条
        hpBar.setOpaque(false); // 必须设置透明
        // 设置进度条的边框为灰色，边框宽度为1像素
        hpBar.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));

        // 滑块组件（反转方向）
        JSlider slider = new JSlider(0, 100, 0);
        //slider.setInverted(true); // 反转滑块方向
        slider.setOpaque(false);//设置组件不透明
        slider.setPaintTrack(false);//不显示滑块轨道
        slider.setPaintLabels(false);

        // 实现点击跳转功能
        slider.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mousePressed(java.awt.event.MouseEvent e) {
                JSlider sourceSlider = (JSlider) e.getSource();
                try {
                    //强制转换为 BasicSliderUI
                    BasicSliderUI ui = (BasicSliderUI) sourceSlider.getUI();

                    // 反射调用 protected 方法
                    java.lang.reflect.Method method = BasicSliderUI.class.getDeclaredMethod(
                            "valueForXPosition", int.class
                    );
                    method.setAccessible(true);
                    int value = (int) method.invoke(ui, e.getX());

                    // 值域约束
                    value = Math.max(0, Math.min(100, value));
                    sourceSlider.setValue(value);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(frame,
                            "当前主题不支持点击跳转功能",
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                }
            }
        });
        // 滑块监听交互设置
        slider.addChangeListener(e -> {
            int sliderValue = slider.getValue();
            // 血条值 = 滑块值（实现方向同步）
            int hpValue = 100 - sliderValue;
            hpBar.setValue(hpValue);
            hpBar.setString(hpValue + "%");

            // 血量为0时触发统计
            if (hpValue == 0 && sliderValue == 100) {
                updateCounter();
                updateResultPanel(); //更新结果面板
            } else if (hpValue > 0 && sliderValue < 100) {
                updateCounter(); // 恢复状态时也更新
                updateResultPanel(); //更新结果面板
            }
        });

        // 组件叠加
        hpPanel.add(slider);
        hpPanel.add(hpBar);

        //更新结果面板
        spiritCombo.addActionListener(e -> updateResultPanel());

        // 组装面板
        panel.add(spiritCombo, BorderLayout.WEST);
        panel.add(hpPanel, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createResultPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        resultTextPane = new JTextPane();

        // 复选框面板
        JPanel checkBoxPanel = new JPanel();
        checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.X_AXIS));
        checkBoxPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));

        // 初始化复选框
        checkBeikezhi = createCheckBox("被克制", true);
        checkKezhi = createCheckBox("克制", false);
        checkWeiruo = createCheckBox("微弱", false);
        checkWuxiao = createCheckBox("无效", false);
        // 添加监听器
        ItemListener checkListener = e -> updateCheckBoxStates();
        checkBeikezhi.addItemListener(checkListener);
        checkKezhi.addItemListener(checkListener);
        checkWeiruo.addItemListener(checkListener);
        checkWuxiao.addItemListener(checkListener);
        // 添加组件
        checkBoxPanel.add(checkBeikezhi);
        checkBoxPanel.add(Box.createHorizontalStrut(8));
        checkBoxPanel.add(checkKezhi);
        checkBoxPanel.add(Box.createHorizontalStrut(8));
        checkBoxPanel.add(checkWeiruo);
        checkBoxPanel.add(Box.createHorizontalStrut(8));
        checkBoxPanel.add(checkWuxiao);

        panel.add(checkBoxPanel, BorderLayout.NORTH);

        // 创建结果文本区域
        resultTextPane.setEditable(false);
        resultTextPane.setMargin(new Insets(1, 6, 1, 5));// 设置边距
        resultTextPane.setEditorKit(new WrapEditorKit());// 自动换行

        JScrollPane scrollPane = new JScrollPane(
                resultTextPane,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,//滚轮条从不出现
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
        );
        scrollPane.setPreferredSize(new Dimension(0, 168)); // 设置滚动面板固定高度高度160像素

        panel.add(scrollPane, BorderLayout.CENTER);
        resultTextPane.setBackground(frame.getBackground());
        return panel;
    }
    private void updateResultPanel() {
        List<String> attackTypes = new ArrayList<>();
        Component mainPanel = frame.getContentPane().getComponent(0);
        for (Component comp : ((Container) mainPanel).getComponents()) {
            if (comp instanceof JPanel) {
                JComboBox<String> combo = findComboInPanel((JPanel) comp);
                JProgressBar bar = findProgressBarInPanel((Container) comp);
                if (combo != null && bar != null && bar.getValue() > 0) {
                    String selected = (String) combo.getSelectedItem();
                    selected = convertSpecialSpirit(selected);
                    attackTypes.add(selected);
                }
            }
        }

        StringBuilder result = new StringBuilder();
        result.append("<html><style>"
                +".bStrong {color:green;}"
                + ".strong {color:red;} "
                + ".weak {color:blue;} "
                + ".invalid {color:gray;} "
                + "p {margin: 2px 0;}" // 添加段落样式
                + "</style>");

        // 根据复选框状态显示标题
        List<String> titles = new ArrayList<>();
        if(checkBeikezhi.isSelected()) titles.add("被克制");
        if(checkKezhi.isSelected()) titles.add("克制");
        if(checkWeiruo.isSelected()) titles.add("微弱");
        if(checkWuxiao.isSelected()) titles.add("无效");
        // 使用<p>标签包裹每一行
        result.append("<p>精灵——<span class='bStrong'>被克制</span>——<span class='strong'>克制</span>——<span class='weak'>微弱</span>——<span class='invalid'>无效</span></p>"); // 修改这里

        for (String attack : attackTypes) {
            Map<String, Double> defendMap = restraintMap.getOrDefault(attack, new HashMap<>());
            Map<String, List<String>> reversed = getReversedRestraints(attack);

            List<String> parts = new ArrayList<>();
            if(checkBeikezhi.isSelected()) {
                parts.add(getColoredList(reversed.get("strong"), "bStrong"));
            }
            if(checkKezhi.isSelected()) {
                parts.add(getColoredList(getStrongDefenders(defendMap), "strong"));
            }
            if(checkWeiruo.isSelected()) {
                parts.add(getColoredList(getWeakDefenders(defendMap), "weak"));
            }
            if(checkWuxiao.isSelected()) {
                parts.add(getColoredList(getInvalidDefenders(defendMap), "invalid"));
            }

            result.append(String.format("<p>%s—%s</p>",
                    attack,
                    String.join("—", parts)
            ));
        }
        result.append("</html>");
        resultTextPane.setContentType("text/html"); // 关键设置
        resultTextPane.setText(result.toString());
    }

    // 克制信息输出
    private String getColoredList(List<String> items, String className) {
        return items.isEmpty() ? "无" :
                String.format("<span class='%s'>%s</span>", className, String.join("，", items));
    }

    private List<String> getStrongDefenders(Map<String, Double> map) {
        return getDefendersByCoeff(map, 2.0);
    }

    private List<String> getWeakDefenders(Map<String, Double> map) {
        return getDefendersByCoeff(map, 0.5);
    }

    private List<String> getInvalidDefenders(Map<String, Double> map) {
        return getDefendersByCoeff(map, 0.0);
    }

    private List<String> getDefendersByCoeff(Map<String, Double> map, double coeff) {
        List<String> result = new ArrayList<>();
        map.forEach((k, v) -> {
            if(v == coeff) result.add(k);
        });
        return result;
    }

    // 查询哪些属性克制当前属性
    private Map<String, List<String>> getReversedRestraints(String defendType) {
        Map<String, List<String>> result = new HashMap<>();
        result.put("strong", new ArrayList<>());
        result.put("weak", new ArrayList<>());
        result.put("invalid", new ArrayList<>());

        // 遍历所有可能的攻击方
        for (String attacker : restraintMap.keySet()) {
            Map<String, Double> relations = restraintMap.get(attacker);
            Double coeff = relations.get(defendType);
            if (coeff == null) continue;

            if (coeff == 2.0) {
                result.get("strong").add(attacker);
            } else if (coeff == 0.5) {
                result.get("weak").add(attacker);
            } else if (coeff == 0.0) {
                result.get("invalid").add(attacker);
            }
        }
        return result;
    }

    // 复选框创建类
    private JCheckBox createCheckBox(String text, boolean selected) {
        JCheckBox checkBox = new JCheckBox(text, selected);
        checkBox.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        checkBox.setFocusPainted(false);
        checkBox.setContentAreaFilled(false);
        return checkBox;
    }

    // 更新复选框状态和窗口宽度
    private void updateCheckBoxStates() {
        int selectedCount = getSelectedCount();

        // 强制至少选择一个
        if (selectedCount == 0) {
            checkBeikezhi.setSelected(true);
            return;
        }

        // 更新窗口宽度
        int newWidth = selectedCount >= 2 ?
                WIDTH_BY_SELECTION[Math.min(selectedCount-2, 2)] :
                frame.getWidth();
        frame.setSize(newWidth, frame.getHeight());

        // 立即刷新结果面板
        updateResultPanel();
    }

    // 计算选中数量
    private int getSelectedCount() {
        return (checkBeikezhi.isSelected() ? 1 : 0) +
                (checkKezhi.isSelected() ? 1 : 0) +
                (checkWeiruo.isSelected() ? 1 : 0) +
                (checkWuxiao.isSelected() ? 1 : 0);
    }
    private String convertSpecialSpirit(String spirit) {
        switch (spirit) {
            case "丽莎布布": return "草";
            case "魔焰猩猩": return "火";
            case "鲁斯王": return "水";
            default: return spirit;
        }
    }
    private JComboBox<String> findComboInPanel(JPanel panel) {
        for (Component comp : panel.getComponents()) {
            if (comp instanceof JComboBox) {
                return (JComboBox<String>) comp;
            }
        }
        return null;
    }
    private JProgressBar findProgressBarInPanel(Container container) {
        for (Component comp : container.getComponents()) {
            if (comp instanceof JProgressBar) {
                return (JProgressBar) comp;
            } else if (comp instanceof Container && !(comp instanceof JComboBox)) {
                JProgressBar bar = findProgressBarInPanel((Container) comp);
                if (bar != null) return bar;
            }
        }
        return null;
    }

    //更新剩余精灵数
    private void updateCounter() {
        // 统计血量归零的精灵数量
        remainingEnemies = countAliveSpirits(frame.getContentPane());
        // 强制更新计数器标签
        counterLabel.setText("剩余：" + remainingEnemies);
        counterLabel.repaint(); // 立即重绘标签
        frame.repaint();
    }

    private void resetAll() {
        // 递归重置滑块
        resetSlidersInContainer(frame.getContentPane());

        // 递归重置下拉框
        resetCombosInContainer(frame.getContentPane());

        // 重置计数器并更新显示
        remainingEnemies = 6;
        counterLabel.setText("剩余：" + remainingEnemies);

        counterLabel.repaint();
        updateResultPanel();
    }

    // 递归重置下拉框
    private void resetCombosInContainer(Container container) {
        for (Component comp : container.getComponents()) {
            if (comp instanceof JComboBox) {
                JComboBox<String> combo = (JComboBox<String>) comp;
                Integer index = (Integer) combo.getClientProperty("defaultIndex");
                if (index != null && index < DEFAULT_SELECTIONS.length) {
                    combo.setSelectedItem(DEFAULT_SELECTIONS[index]);
                }
            } else if (comp instanceof Container) {
                resetCombosInContainer((Container) comp); // 保持容器类型一致
            }
        }
    }

    // 新增递归容器遍历方法
    private void resetSlidersInContainer(Container container) {
        for (Component comp : container.getComponents()) {
            if (comp instanceof JSlider) {
                JSlider slider = (JSlider) comp;
                slider.setValue(0);  // 设置最小值 (强制触发事件)
                slider.getModel().setValue(0);  // 直接更新数据模型
            } else if (comp instanceof Container) {
                resetSlidersInContainer((Container) comp);  // 递归遍历
            }
        }
    }

    // 新增递归统计方法
    private int countAliveSpirits(Container container) {
        int count = 0;
        for (Component comp : container.getComponents()) {
            if (comp instanceof JProgressBar) {
                JProgressBar bar = (JProgressBar) comp;
                if (bar.getValue() > 0) {
                    count++;
                }
            } else if (comp instanceof Container) {
                count += countAliveSpirits((Container) comp);
            }
        }
        return count;
    }

    private void loadRelationMatrixFromTextFile() {
        try (BufferedReader br = new BufferedReader(new FileReader("data/restraint.txt"))) {
            // 跳过首行标题
            br.readLine();

            int row = 0;
            String line;
            while ((line = br.readLine()) != null && row < 16) {
                // 清洗数据：移除所有非数字、非小数点、非逗号的字符
                String cleaned = line.replaceAll("[^\\d.,]", "");

                // 分割数值字符串
                String[] values = cleaned.split(",");

                // 确保有效数据长度
                if (values.length != 16) continue;

                // 转换为double并填充矩阵
                for (int col = 0; col < 16; col++) {
                    try {
                        RELATION_MATRIX[row][col] = Double.parseDouble(values[col].trim());
                    } catch (NumberFormatException e) {
                        RELATION_MATRIX[row][col] = 1.0; // 默认值
                    }
                }
                row++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initRelations() {
        for (int i = 0; i < 15; i++) {
            String attacker = DEFAULT_SPIRITS[i];
            Map<String, Double> relations = new HashMap<>();
            for (int j = 0; j < 15; j++) {
                double value = RELATION_MATRIX[i][j];
                if (value != 1) { // 只记录克制关系
                    relations.put(DEFAULT_SPIRITS[j], value);
                }
            }
            restraintMap.put(attacker, relations);
        }
    }

    private static class ReverseProgressBarUI extends BasicProgressBarUI {

        @Override
        protected void paintDeterminate(Graphics g, JComponent c) {
            // 反转绘制方向
            Insets b = progressBar.getInsets();
            int width = progressBar.getWidth();
            int height = progressBar.getHeight();
            int barRectWidth = width - (b.right + b.left);
            int value = progressBar.getValue();
            double progress = (value - progressBar.getMinimum()) / (double) (progressBar.getMaximum() - progressBar.getMinimum()); // 正确计算进度比例
            // 计算填充起始位置
            int fillStart = (int) (barRectWidth * (1.0 - progress));

            // 绘制背景
            g.setColor(progressBar.getBackground());
            g.fillRect(b.left, b.top, barRectWidth, height);

            // 绘制前景（从右向左）
            g.setColor(progressBar.getForeground());
            g.fillRect(b.left + fillStart, b.top,
                    barRectWidth - fillStart, height);
            // 强制绘制文本
            if (progressBar.isStringPainted()) {
                paintString(g, b.left, b.top, width, height, 0, b);
            }
        }

        @Override
        protected void paintString(Graphics g, int x, int y, int width, int height, int amountFull, Insets b) {
            // 居中绘制百分比文本
            Graphics2D g2d = (Graphics2D) g;
            g2d.setFont(new Font(
                    "宋体",       // 字体名称
                    Font.PLAIN,        // 样式（粗体）
                    14                 // 字号
            ));
            String text = progressBar.getString();
            FontMetrics fm = g2d.getFontMetrics();

            // 计算文本位置（绝对居中）
            int textX = x + (width - fm.stringWidth(text)) / 2;
            int textY = y + (height - fm.getHeight()) / 2 + fm.getAscent();

            // 设置文本颜色（与血条前景色一致）
            g2d.setColor(Color.BLACK);
            g2d.drawString(text, textX, textY);
        }
    }

    // 自定义 EditorKit 实现自动换行
    private static class WrapEditorKit extends StyledEditorKit {
        public ViewFactory getViewFactory() {
            return new WrapColumnFactory();
        }

        private static class WrapColumnFactory implements ViewFactory {
            public View create(Element elem) {
                String kind = elem.getName();
                if (kind != null) {
                    if (kind.equals(AbstractDocument.ContentElementName)) {
                        return new WrapLabelView(elem);
                    }
                }
                return new LabelView(elem);
            }
        }

        private static class WrapLabelView extends LabelView {
            public WrapLabelView(Element elem) {
                super(elem);
            }

            public float getMinimumSpan(int axis) {
                return (axis == View.X_AXIS) ? 0 : super.getMinimumSpan(axis);
            }
        }
    }
}

